package com.leyou.search.interceptor;

import com.leyou.auth.entity.UserInfo;
import com.leyou.auth.utils.CookieUtils;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.search.config.JwtProperties;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author CHERRY
 * @date 2018-09-21-11:38
 */

@EnableConfigurationProperties(JwtProperties.class)
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private JwtProperties jwtProperties;

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginInterceptor.class);

    private static final ThreadLocal<UserInfo> THREAD = new ThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求中的cookie
        String token = CookieUtils.getCookieValue(request, jwtProperties.getCookieName());

        if (StringUtils.isBlank(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //解析
        try {
            UserInfo userInfo = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey());
            THREAD.set(userInfo);
            return true;
        } catch (Exception e) {
            LOGGER.error("解析token异常", e);
            //401
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //渲染完成，移除线程局部变量
        THREAD.remove();
    }

    /**
     * 获取线程userinfo
     *
     * @return
     */
    public static UserInfo getUserInfo() {
        return THREAD.get();
    }
}
